import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:sph_shipper/AppConfig/ShowDialog.dart';
import 'package:sph_shipper/SendGoods/MapSiteSelection.dart';


import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
class LoadingAddressView extends StatefulWidget {
  const LoadingAddressView({super.key, required this.addressType, required this.query});
  final int addressType;
  final String query;
  @override
  State<LoadingAddressView> createState() => _LoadingAddressViewState();
}

class _LoadingAddressViewState extends State<LoadingAddressView> {
  Map nowAddressMap={};
  Map detailMap={};
  String detailAddress="";
  List<String> hisAddressLsit=[];
  List searchAddressList=[];
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  BaiduLocation _loationResult = BaiduLocation();
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  late BMFMapController _myMapController;
  bool _suc = false;
  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    ///单次定位时如果是安卓可以在内部进行判断调用连续定位
    if (Platform.isIOS) {
      ///接受定位回调
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _loationResult = result;
          print("result:$result");
        });
      });
    } else if (Platform.isAndroid) {
      ///接受定位回调
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _loationResult = result;
          print(result);
          _myLocPlugin.stopLocation();
          getAndroidLocation();
        });
      });
    }
    _locationAction();

    getHisAddress();
    super.initState();

  }
  // 将String类型转换为Map类型的方法
  Map<String, dynamic>? stringToMap(String jsonString) {
    try {
      // 使用json.decode()将JSON格式的String转换为Map类型
      return json.decode(jsonString);
    } catch (e) {
      // 如果解析失败，则打印错误信息并返回null
      print('Error parsing JSON string: $e');
      return null;
    }
  }

// 将List中的所有String转换为Map类型的方法
  List<Map<String, dynamic>> listStringToListMap(List<String> stringList) {
    List<Map<String, dynamic>> resultList = [];
    // 遍历列表中的每个String，并将其转换为Map类型
    stringList.forEach((string) {
      Map<String, dynamic>? map = stringToMap(string);
      if (map != null) {
        resultList.add(map);
      }
    });
    return resultList;
  }
  //检索地址
  Future<void> searchAddressAction(String query) async {
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    print(position);
    String Latitude=position.latitude.toString();
    String Longitude=position.longitude.toString();
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>(MyServiceUrl.header+ "api/system/dev/cityDict/detailList?query=$query&location=$Latitude,$Longitude")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          setState(() {
            searchAddressList=jsonMap['data'];
            Navigator.pop(context,searchAddressList[0]);
          });


        } else {
          BrnToast.show(jsonMap['msg'], context);
        }



      });
    }).catchError((error) {
      print(error);
    });
  }

  void getHisAddress()async{

  List<String>? hisAddresses = await HisAddressManager.getAddresses();
  if (hisAddresses != null) {
    setState(() {
      hisAddressLsit=hisAddresses;
      hisAddressLsit=hisAddressLsit.toSet().toList();
      print("hisAddressLsit:${hisAddressLsit}") ;
      // hisAddressLsit = listStringToListMap(hisAddresses);
      // Map<String, dynamic> resultMap = json.decode(hisAddresses[0]);
      // print(resultMap);
      // print("hisAddressLsit:${json.decode(hisAddressLsit[0])}");
    });
  } else {
    // 处理未找到存储的地址列表的情况
    print('No addresses found');
  }
}
  List addressList=["苏州速搜物流科技有限公司","苏州速搜物流科技有限公司","苏州速搜物流科技有限公司"];

  /// 设置地图参数
  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        coorType: 'bd09ll',
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        locationPurpose: BMFLocationPurpose.sport,
        coordType: BMFLocationCoordType.bd09ll);
    return options;
  }

  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best);
    return options;
  }
  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    var status = await Permission.location.request();
      // var status = await Permission.location.status;
      if (status==PermissionStatus.denied) {
        showLocFirstDialog(context);
        await Permission.location.request();
      }else if(status==PermissionStatus.permanentlyDenied){
        showLocDialog(context);
      }else{
        _startLocation();
        getLocation();
      }

    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);
    print('设置定位参数：$iosMap');
  }
  /// 启动定位
  Future<void> _startLocation() async {
    if (Platform.isIOS) {
      _suc = await _myLocPlugin
          .singleLocation({'isReGeocode': true, 'isNetworkState': true});
      print('开始单次定位：$_suc');
    } else if (Platform.isAndroid) {
      _suc = await _myLocPlugin.startLocation();
      ///接受定位回调
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _loationResult = result;
          print(result);
          _myLocPlugin.stopLocation();
          getAndroidLocation();
        });
      });
    }
  }

  void getLocation() async {
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

    String Latitude=position.latitude.toString();
    String Longitude=position.longitude.toString();
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    //nmk6gFoaaPXmiWx1GEkqGD4e5GIogdUT  Pb9qx5M4d02snVGSQaEqGVpqybA18AS8  0t6rhRWUGmqtbsMRMBVSqzbBwBrCzXLj
    dio.get<String>("https://api.map.baidu.com/reverse_geocoding/v3/?ak=nmk6gFoaaPXmiWx1GEkqGD4e5GIogdUT&output=json&coordtype=wgs84ll&location=$Latitude,$Longitude")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['status'].toString();
        if (code == "0") {
            nowAddressMap=jsonMap['result'];
        } else {}
        // 打印结果
        print('result: ${jsonMap['result'].toString()}');
      });
    }).catchError((error) {
      print(error);
    });
  }
  void getAndroidLocation() async {

    String Latitude=_loationResult.latitude.toString();
    String Longitude=_loationResult.longitude.toString();
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    //nmk6gFoaaPXmiWx1GEkqGD4e5GIogdUT  Pb9qx5M4d02snVGSQaEqGVpqybA18AS8  0t6rhRWUGmqtbsMRMBVSqzbBwBrCzXLj
    dio.get<String>("https://api.map.baidu.com/reverse_geocoding/v3/?ak=0t6rhRWUGmqtbsMRMBVSqzbBwBrCzXLj&output=json&coordtype=wgs84ll&location=$Latitude,$Longitude")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['status'].toString();
        if (code == "0") {
          nowAddressMap=jsonMap['result'];
        } else {

        }
        // 打印结果
        print('result: ${jsonMap['result'].toString()}');
      });
    }).catchError((error) {
      print(error);
    });
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        centerTitle: true,
        backgroundColor: Colors.white,

        title: Text(widget.addressType==1? "装货地址":"卸货地址",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: Column(
        children: [
          Expanded(child:   ListView(
            children: [
              Container(
                color: Colors.white,
                padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 20.w,right: 20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("详细地址",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        GestureDetector(
                          child:   Container(
                              width:220.w,
                              height: 30.h,
                              decoration: BoxDecoration(
                                  color: MyColors.backgreyColor,
                                  borderRadius: BorderRadius.all(Radius.circular(10))),
                              child:Center(
                                child:   detailAddress==""?
                                Text(widget.addressType==1?"必填，请输入装货详细地址":"必填，请输入卸货详细地址",style: TextStyle(color: MyColors.hintColor,fontSize: 14.sp),)
                                    :Text(detailAddress,overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                              ),
                          ),
                          onTap: ()async{
                            final result=await showModalBottomSheet(context: context, builder: (BuildContext context) {
                              return checkDetialAddressSheet(region: widget.query,
                              );});
                            if (result !=null){
                                setState(() {
                                  detailMap=result;
                                  detailAddress=detailMap['address'];
                                });
                            }
                          },
                        ),

                        BrnIconButton(
                            name: '地图选址',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color:Colors.black,
                            ),
                            direction: Direction.bottom,
                            padding: 4,
                            iconHeight: 18.h,
                            iconWidth: 18.w,
                            iconWidget:Image.asset("lib/Images/OrderList/发货地图选址icon.png",width: 18.w,height: 18.h,),
                            onTap: () async{
                              final result =await  Navigator.push( context, FadeRoute(page:MapSiteSelection(
                                nowLocMap: nowAddressMap,
                              )));
                            if(result!=null){
                              setState(() {
                                detailAddress=result['formatted_address'];
                                detailMap={
                                  "name":detailAddress,
                                  "location":{
                                    "lat":result['location']['lat'],
                                    "lng":result['location']['lng'],
                                  },
                                  "province":result['addressComponent']['province'],
                                  "city":result['addressComponent']['city'],
                                  "district":result['addressComponent']['district'],
                                  "adcode":result['addressComponent']['adcode'],
                                  "address":detailAddress,
                                };
                              });

                            }
                            }),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 20.w,right: 20.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("联系人信息",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(10))),
                          width: 130.w,
                          height: 40.h,
                          child:  TextField(
                            decoration: InputDecoration(
                              hintText: widget.addressType==1?'请输入装货人姓名':"请输入卸货人姓名",
                              hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                              filled: true,
                              fillColor: MyColors.backgreyColor,
                              border: InputBorder.none,
                              alignLabelWithHint: true,
                              contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal: 6.0.w),
                            ),
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.left,
                            style: TextStyle(color: Colors.black),
                            onChanged: (value) {
                              setState(() {
                                print(value);
                              });
                            },
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(10))),
                          width: 140.w,
                          height: 40.h,
                          child:  TextField(
                            decoration: InputDecoration(
                              hintText: '请输入电话号码',
                              hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                              filled: true,
                              fillColor: MyColors.backgreyColor,
                              border: InputBorder.none,
                              alignLabelWithHint: true,
                              contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal: 6.0.w),
                            ),
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.left,
                            style: TextStyle(color: Colors.black),
                            onChanged: (value) {
                              setState(() {
                                print(value);
                              });
                            },
                          ),
                        ),
                      ],
                    ),


                  ],
                ),
              ),
              GestureDetector(
                child:    Container(
                  margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                  padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 20.w,right: 20.w),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Image.asset("lib/Images/OrderList/发货当前位置icon.png",width: 20.w,height: 20.h,),
                          Container(
                            width: screenSize.width-150.w,
                            child:Text(nowAddressMap.isNotEmpty? nowAddressMap['formatted_address']:"",overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 13.sp),),

                          ),
                          SizedBox(width: 8.w,),
                          BrnTagCustom(
                            tagText: "当前位置",
                            backgroundColor: MyColors.themeColor,
                            fontSize: 10.sp,
                          ),
                        ],
                      ),
                      if(nowAddressMap.isNotEmpty)
                        Row(
                          children: [
                            SizedBox(width: 20.w,),
                            Container(
                              width: 200.w,
                              child:Text(nowAddressMap['addressComponent']['province']+nowAddressMap['addressComponent']['city']+nowAddressMap['addressComponent']['district']+nowAddressMap['addressComponent']['town'],overflow: TextOverflow.ellipsis,style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                            )
                          ],
                        ),
                    ],
                  ),
                ),
                onTap: (){
                  setState(() {
                    detailAddress=nowAddressMap['formatted_address'];
                    detailMap={
                      "name":nowAddressMap['formatted_address'],
                      "location":{
                        "lat":nowAddressMap['location']['lat'],
                        "lng":nowAddressMap['location']['lng'],
                      },
                      "province":nowAddressMap['addressComponent']['province'],
                      "city":nowAddressMap['addressComponent']['city'],
                      "district":nowAddressMap['addressComponent']['district'],
                      "adcode":nowAddressMap['addressComponent']['adcode'],
                      "address":nowAddressMap['formatted_address'],
                    };
                  });
                },
              ),

              Container(
                margin: EdgeInsets.only(top: 8.h,left: 30.w,),
                child:  Text("历史地址",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
              ),
              Container(
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,bottom: 8.h),
                height: 250.h,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: ListView.builder(
                    // physics: NeverScrollableScrollPhysics(),
                    itemCount: hisAddressLsit.length>5?5:hisAddressLsit.length,
                    itemBuilder: (BuildContext context, int index) {
                      return GestureDetector(
                        child:  Container(
                          padding: EdgeInsets.only(left: 10.w,right: 10.w,top:8.h,bottom: 8.h ),
                          child:  Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Image.asset("lib/Images/OrderList/发货当前位置icon.png",width: 20.w,height: 20.h,color: MyColors.textColor,),
                                    Container(
                                      width: screenSize.width-100.w,
                                      child:   Text(hisAddressLsit.reversed.toList()[index],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                    ),

                                    SizedBox(width: 8.w,),

                                  ],
                                ),
                                // Row(
                                //   children: [
                                //     SizedBox(width: 20.w,),
                                //     // Text(hisAddressLsit[index],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                //   ],
                                // ),
                                SizedBox(height:10.h,),
                                if(index<addressList.length-1) Divider(height: 1.h,color: MyColors.backgreyColor,),
                              ],
                            ),

                        ),
                        onTap: (){
                          searchAddressAction(hisAddressLsit.reversed.toList()[index]);
                        },
                      )
                       ;
                    }),
              )
            ],
          ),
          ),
          Container(
            height: 85.h,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top: 10.h,bottom: 40.h),
            color: Colors.white,
            child: BrnSmallMainButton(
              width: screenSize.width-30.w,
              title: '确认',
              bgColor: MyColors.themeColor,
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              radius: 30,
              onTap: () async{
               hisAddressLsit.add(detailMap['address']);
                await HisAddressManager.saveAddresses(hisAddressLsit);
              Navigator.pop(context,detailMap);
              },
            ),
          ),
        ],
      )

    );
  }
}
class checkDetialAddressSheet extends StatefulWidget {
  const checkDetialAddressSheet({super.key, required this.region});
  final String region;
  @override
  State<checkDetialAddressSheet> createState() => _checkDetialAddressSheetState();
}

class _checkDetialAddressSheetState extends State<checkDetialAddressSheet> {
  List dataList=[];
  Future<void> searchAddressAction(String query) async {
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>(MyServiceUrl.header+ "api/system/dev/cityDict/detailList?query=$query&region=${widget.region}")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());

        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          dataList=jsonMap['data'];
          dataList = dataList.where((dict) {
            return dict['address'] != null && dict['address'].toString().isNotEmpty;
          }).toList();
          print(dataList);
        } else {
          BrnToast.show(jsonMap['msg'], context);
        }



      });
    }).catchError((error) {
      print(error);
    });
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Container(
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 15.h),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: Column(
        children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                  SizedBox(width: 10.w,),
                Text("请输入详细地址",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                GestureDetector(
                  child: Icon(Icons.close,color: MyColors.authTipColor,size: 30,),
                  onTap: (){
                    Navigator.pop(context);
                  },
                ),
              ],
            ),
          SizedBox(height: 10.h,),
          Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10))),
            width:screenSize.width-20.w,
            height: 40.h,
            child:  TextField(
              decoration: InputDecoration(
                hintText: '请输入详细地址',
                hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.hintColor),
                filled: true,
                fillColor: MyColors.backgreyColor,
                border: InputBorder.none,
                alignLabelWithHint: true,
                contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal: 6.0.w),
              ),
              textAlign: TextAlign.left,
              style: TextStyle(color: Colors.black),
              onChanged: (value) {
                setState(() {
                  searchAddressAction(value);
                });
              },
            ),
          ),
          SizedBox(height: 10.h,),
          Container(
            width: screenSize.width-20.w,
            height: 270.h,
            color: Colors.white,
            child:  ListView.builder(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                itemCount: dataList.length,
                itemBuilder: (BuildContext context,
                    int index) {
                  return GestureDetector(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(dataList[index]['address'],style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                        Divider(height: 16.h,color: MyColors.backgreyColor,),
                      ],
                    ),
                    onTap: (){
                        print(dataList[index]);
                      Navigator.pop(context,dataList[index]);
                    },
                  );
                }
                ),
          )
        ],
      ),
    );
  }
}
